﻿using System.Collections.Generic;
using System.Linq;
using DesignPatterns.BuilderPattern.Models;

namespace DesignPatterns.BuilderPattern.Repositories
{
    /// <summary>
    /// Notice how this interface doesn't contain the methods to get/save address for a person.
    /// This only contains the method to get addresses. 
    /// </summary>
    public interface IWebsiteRepository 
    {
        Dictionary<int, string> GetAll();
        string GetById(int id);
    }

    /// <summary>
    /// The single responsibility for this class is to get and save address to the database
    /// </summary>
    public class WebsiteRepository : IPersonBuilder, IWebsiteRepository
    {
        public Dictionary<int, string> GetAll()
        {
            return new Dictionary<int, string>
            {
                {1, "www.google.com"},
                {2, "www.stackoverflow.com"},
                {3, "www.visualstudio.com"},
                {4, "www.microsoft.com"},
                {5, "www.asp.net"}
            };
        }

        public string GetById(int id)
        {
            return GetAll().FirstOrDefault(i => i.Key == id).Value;
        }

        public List<string> GetByPerson(int personId)
        {
            /****** THIS METHOD WOULD BE EASY TO UNIT/INTEGRATION TEST ******/

            //Query the database to get address for this person id
            //this would probably be a many to many table
            return GetAll().Where(i => new[] {1, 2, 5}.Contains(i.Key)).Select(i => i.Value).ToList();
        }

        public void SaveWebsiteForPerson(int personId, List<string> websites)
        {
            /****** THIS METHOD WOULD BE EASY TO UNIT/INTEGRATION TEST ******/

            //Save the many to many relations to the database
        }


        public void Populate(ref Person item)
        {
            if (item == null) return;

            item.FavoriteWebSites = GetByPerson(item.Id);
        }

        public void Save(ref Person item)
        {
            if (item == null) return;
            
            SaveWebsiteForPerson(item.Id, item.FavoriteWebSites);
        }
    }
}
